<template >
  <div class="roadmap-container-ai">
    <a-row>
      <a-col :span="16" class="list-container">
        <a-row class="operate-row">
          <a-col :span="10">{{$t('hangManage.roadList')}}</a-col>
          <a-col :span="14" class="text-right">
            <a-space>
              <a-button type="primary" @click="toggleAll(true)">{{ $t('common.expandAll') }}</a-button>
              <a-button type="primary" @click="toggleAll(false)">{{ $t('common.packUpAll') }}</a-button>
              <a-button type="warning" @click="clearList" >{{ $t('common.clearList') }}</a-button>
            </a-space>
          </a-col>
        </a-row>
        <header>
          <div v-for="(item, index) in routeHeader" :key="index">{{item}}</div>
        </header>
        <a-spin :spinning="loading">
          <draggable :list="tableList" is='draggable'  filter=".forbid" handle=".process-box" animation="300" :scroll="true" force-fallback="true" group="out" item-key="index" :allbackOnBody="true" @add="add" @sort="handleSort" @start="handleStart" style="min-height: calc(100vh - 515px)">
            <template #item="{element, index}">
              <div :class="{'forbid': index== 0}">
                <div class="relative">
                  <span class="toggle-box forbid">
                    <img
                        v-if="element.forwardMerge"
                        src="../../../../assets/images/merge.png"
                        alt="#"
                    />
                    <minus-square-outlined v-else-if="element.open" @click="() => {element.open = false}" />
                    <plus-square-outlined v-else @click="() =>{ element.open = true}" />
                  </span>
                  <div class="mt-12 process-box"
                       :class="element.moProcRoadmapProcStationList?.length > 0 ?
                       '': element.forwardMerge? 'process-box-merge'
                        : 'process-box-empty'
                    "
                  >
                    <div>
                      <span>{{element.sort}}</span>
                    </div>
                    <div>
                      <a-checkbox class="forbid" v-model:checked="element.enable"  :disabled="index ==0">{{ $t('hangManage.effect') }}</a-checkbox>
<!--                      <a-checkbox class="forbid" v-model:checked="element.enable"  :disabled="index ==0" @change="(e) => changeProcessInfo(!e.target.checked)">{{element.enable}}{{ $t('hangManage.effect') }}</a-checkbox>-->
                    </div>
                    <div>
                      <a-checkbox class="forbid" v-model:checked="element.forwardIntegration" @change="onCheckChange(element)" :disabled="index ==0">{{ $t('other.forwardMerge') }}</a-checkbox>
                    </div>
                    <div>{{ element.processNo }}，{{ element.name }}</div>
                    <div class="forbid"></div>
                    <div class="forbid">
                      <span class="close-icon" v-if="index!=0" @click="handelCancel(index, false)">
                        <close-outlined />
                      </span>
                    </div>
                  </div>
                </div>
                <draggable v-model="element.moProcRoadmapProcStationList" filter=".nodrag" is='draggable' animation="300" force-fallback="true" group="inner" item-key="index" :allbackOnBody="true" @add="addInner" :disabled="disabled" @start="handleInnerStart">
                  <template v-slot:item="item">
                    <div class="site-box" v-if="element.open">
                      <div class="relative">
                        <span class="line-icon">
                          <environment-two-tone two-tone-color="#3E8FF7" />
                        </span>
                        <span class="pl-15">
                              {{getFieldText(lineList,item.element.stationId,'id','lineNo')}}-{{getFieldText(lineList,item.element.stationId,'id','stationNo')}}
<!--                          {{item.element.lineNo}}-{{item.element.stationNo}}-->
                        </span>
                      </div>
                      <div>
                        <a-checkbox v-model:checked="item.element.mainStationBoolean" class="nodrag">{{ $t('other.assistSit') }}</a-checkbox>
                      </div>
                      <div>
                        <a-checkbox v-model:checked="item.element.receiveHangerBoolean">{{ $t('hangManage.receiveHanger') }}</a-checkbox>
                      </div>
                      <div>
                        {{item.element.type == 1 ? $t('other.save'): $t('other.normal')}}
                        <span v-if="showMsg(item.element, 'all')"> ，（ </span>
                        <span v-if="showMsg(item.element, 'color')">{{ $t('basicData.color') }}：{{item.element.colorList.join(',')}}；</span>
                        <span v-if="showMsg(item.element, 'size')">{{ $t('basicData.size') }}： {{item.element.sizeList.join(',')}}；</span>
                        <span v-if="showMsg(item.element, 'po')">PO： {{item.element.poList.join(',')}}；</span>
                        <span v-if="showMsg(item.element, 'cutterNo')">{{$t('hangManage.bedNo')}}： {{item.element.cutterNoList.join(',')}}；</span>
                        <span v-if="showMsg(item.element, 'tailorBill')">{{$t('hangManage.cut')}}： {{item.element.tailorBillList.join(',')}}</span>
                        <span v-if="showMsg(item.element, 'all')"> ）</span>
                      </div>

                      <div>
                            <span v-if="item.element.staffId"> {{getFieldText(staffList,item.element.staffId,'id','staffNo')}}-{{getFieldText(staffList,item.element.staffId,'id','nickName')}}
                              {{getFieldText(staffList,item.element.staffId,'id','skillGrade')}}
                              {{arrToStr(staffList,item.element.staffId,'id','professionNameList')}}
                            </span>
                      </div>
                      <div v-if="!disabled" class="nodrag">
                        <a-button type="link" class="primary-link" @click="editSite(index, item.index, item.element)">{{ $t('common.editor') }}</a-button>
                        <span class="close-icon" @click="handelCancel(item.index, true, index)">
                          <close-outlined />
                        </span>
                      </div>
                    </div>
                  </template>
                </draggable>
              </div>

            </template>
          </draggable>
        </a-spin>
      </a-col>
      <a-col :span="8 " class="choose-container">
<!--        {{processSelectList}}-->
        <ChooseList ref="chooseListRef"   :processSelectList = "processSelectList" :moId="props.moId "
                     :tableList="tableList" @onOutGroupEnd="onOutGroupEnd" @onChooseProcess="onChooseProcess"
                    @onInnerGroupEnd="onInnerGroupEnd" :operateType="props.operateType" />
      </a-col>
    </a-row>
    <editStation ref="editStationRef" @ok="onStationOK" />
  </div>
</template>

<script setup>
import draggable from 'vuedraggable'
import {ref, watch, nextTick, onMounted} from 'vue'
import { routeHeader } from './routeChartConfig'
// import { routeHeader } from './Config'
import {  getFieldText } from '@/utils'
import { PlusSquareOutlined, MinusSquareOutlined, CloseOutlined, EnvironmentTwoTone } from '@ant-design/icons-vue'
import ChooseList from './chooseList.vue'
import editStation from './editStation.vue'
import { cloneDeep, uniqBy } from 'lodash'
import { message } from 'ant-design-vue'
import axios from "@/utils/request"
import i18n from '@/locales/index'
const { t } = i18n.global
let emits = defineEmits(['initFormInfo', 'onProcessInfo'])
let props = defineProps({
  roueteVersionId: {
    require: true,
    default: () => null
  },
  moId: {
    require: true,
    default: () => null
  },
  moInfo: {
    require: true,
    default: () => { }
  },
  operateType: {
    require: true,
    default: () => ''
  },
  dataAll: {
    require: true,
    default: () => Object
  },
  lineStationLists: {
    require: true,
    default: () => Object
  }
})
let disabled = ref(false)
let loading = ref(false)
let editStationRef = ref()
let tableList = ref([])
let dataAll = ref()
let processSelectList = ref({})
let routeInfo = ref({})
let chooseListRef = ref({})
let originList = ref(tableList.value)
let sortFlag = ref(false)
let sortInnerFlag = ref(false)
let processId = ref(null)
let editProcIndex = ref(0)
let editStationIndex = ref(0)
let isAdd = ref(false)
let isEdit = ref(false)
let originSortList = ref([])
let maxNum = ref(0)
let lineList = ref(props.lineStationLists)

let staffList = ref([])
const arrToStr = (ary, value, itemName, field) => {
  const info = ary.filter(i => i[itemName] == value)
  let arr =  info.length ? info[0][field] : []
  return arr ? `(${ arr.join(",")})` : ''
}

const handleStart = () => {
  sortFlag.value = true
  originList.value = cloneDeep(tableList.value)
}
const changeProcessInfo = (isDelete) => {
  let optList = tableList.value.filter(i => i.effect)
  emits('onProcessInfo', optList, isDelete)
}
const add = async (e) => {
  sortFlag.value = false
  await nextTick()
  if (e.newIndex === 0) {
    message.warning(t('other.firstStationMCanHang') )
    tableList.value.splice(0, 1)
    initSortInfo()
  }
  changeProcessInfo()
}
const handleSort = (e) => {
  if (sortFlag.value) {
    if (e.newIndex == 0) {
      message.warning(t('other.firstStationMCanHangProcess'))
      tableList.value = originList.value
    } else {
      initSortInfo()
      tableList.value.forEach((i, index) => { i.sort = originSortList.value[index] })
    }
  }
}
const handelCancel = (key, isInner, outKey) => {
  if (isInner) {
    tableList.value[outKey].moProcRoadmapProcStationList.splice(key, 1)
  } else {
    tableList.value.splice(key, 1)
    initSortInfo()
    changeProcessInfo(true)
  }
}
const onOutGroupEnd = () => {
  tableList.value = tableList.value.map(i => {
    let obj = { ...i }
    if (obj.open == undefined) obj.open = true
    obj.moProcRoadmapProcStationList = obj.moProcRoadmapProcStationList || []
    if (!obj.sort) {
      let newSortNo = ++maxNum.value
      obj.sort = newSortNo
    }
    return obj
  })
  initSortInfo()

  tableList.value.forEach((i, index) => { i.sort = originSortList.value[index] })
}
const handleInnerStart = () => {
  sortInnerFlag.value = true
  originList.value = cloneDeep(tableList.value)
}
const onSortInner = () => {
  let lists = cloneDeep(tableList.value)
  let flag1 = lists[0].moProcRoadmapProcStationList.some(i => i.role != '2')
  lists.splice(0, 1)
  let flag2 = lists.reduce((prev, next) => {
    return prev.concat(...(next.moProcRoadmapProcStationList ? next.moProcRoadmapProcStationList : []))
  }, []).some(i => i.role == 2)
  if (flag1) message.warning(t('other.firstProcessCanHang'))
  if (flag2) message.warning(t('other.hangStationMustDownFirstProcessCanHang'))
  let mergeFlag = lists.some(i => i.forwardMerge && i.moProcRoadmapProcStationList.length > 0)
  if (mergeFlag) message.warning(t('other.forwardMergeProcess'))
  let isUniq = lists.every(i => isUniqInner(i.moProcRoadmapProcStationList).isUniq)
  if (flag1 || flag2 || mergeFlag || !isUniq) tableList.value = originList.value
}
const isUniqInner = (list) => {
  let uniqList = uniqBy(list, 'stationId')
  let isUniq = uniqList.length == list.length
  if (!isUniq) message.warning(t('other.sameProcessCanNotSameStation'))
  return {
    isUniq,
    uniqList
  }
}
const onAddInner = () => {
  tableList.value.forEach((el, index) => {
    if (index == 0) {
      if (el.moProcRoadmapProcStationList && el.moProcRoadmapProcStationList.some(i => i.role != '2')) {
        message.warning(t('other.firstProcessCanHang'))
        el.moProcRoadmapProcStationList = el.moProcRoadmapProcStationList.filter(i => i.role == '2')
      }
      let isUniqInfo = isUniqInner(el.moProcRoadmapProcStationList)
      if (!isUniqInfo.isUniq) el.moProcRoadmapProcStationList = isUniqInfo.uniqList
    } else {
      if (el.forwardMerge) {
        if (el.moProcRoadmapProcStationList.length > 0) {
          message.warning(t('other.forwardMergeProcess'))
          el.moProcRoadmapProcStationList = []
        }
      } else {
        if (el.moProcRoadmapProcStationList && el.moProcRoadmapProcStationList.some(i => i.role == '2')) {
          message.warning(t('other.hangStationMustDownFirstProcessCanHang'))
          el.moProcRoadmapProcStationList = el.moProcRoadmapProcStationList.filter(i => i.role != '2')
        }

        let isUniqInfo = isUniqInner(el.moProcRoadmapProcStationList)
        if (!isUniqInfo.isUniq) el.moProcRoadmapProcStationList = isUniqInfo.uniqList
      }

    }
  })
}
const addInner = async () => {
  await nextTick()
  if (sortInnerFlag.value) {
    onSortInner()
  } else {
    onAddInner()
  }
  sortInnerFlag.value = false
}
const onInnerGroupEnd = () => {
  tableList.value.map(el => {
    el.moProcRoadmapProcStationList = el.moProcRoadmapProcStationList.map(i => ({ ...i }))
    return el
  })
}
const toggleAll = (open) => {
  tableList.value.forEach(i => {
    i.open = open
  })
}
const clearList = () => {
  let lists = cloneDeep(tableList.value).splice(0, 1)
  lists[0].moProcRoadmapProcStationList = []
  tableList.value = lists
  initSortInfo()
  changeProcessInfo(true)

}
// 向前合并
const onCheckChange = (element) => {
  if (element.forwardIntegration) element.moProcRoadmapProcStationList = []
}
const editSite = (parentIndex, index, record) => {
  // let name = `${record.lineNo}-${record.stationNo}`

  let lineNo1 = getFieldText(lineList.value,record.stationId,'id','lineNo')
  let stationNo1 = getFieldText(lineList.value,record.stationId,'id','stationNo')
  let name = lineNo1 +'-'+ stationNo1
  editProcIndex.value = parentIndex
  editStationIndex.value = index
  editStationRef.value.edit(name, record, props.moInfo, staffList.value)
  // editStationRef.value.edit(name, record, props.moInfo, props.staffList)
}
const onStationOK = (value) => {
  let datas = cloneDeep(tableList.value)
  datas.forEach((item, index) => {
    if (index == editProcIndex.value) {
      item.moProcRoadmapProcStationList && item.moProcRoadmapProcStationList.map((el, i) => {
        if (i == editStationIndex.value) {
          Object.assign(el, value)
        }
        return el
      })
    }
  })
  tableList.value = datas
}

const initSortInfo = () => {
  originSortList.value = tableList.value.map(i => i.sort).filter(i => i != undefined).sort((a, b) => a - b)
  maxNum.value = Math.max(...originSortList.value)
}
const initTableList = (list, isNew) => {
  list.forEach(i => {
    i.open = true
    i.forwardMerge = i.forwardIntegration == 1
    i.enable = isNew ? 1 : i.enable
    i.effect = i.enable == 1
    if (i.moProcRoadmapProcStationList) {
      i.moProcRoadmapProcStationList.forEach(i => {
        i.mainStationBoolean = i.mainAuxiliaryStation == 2
        i.receiveHangerBoolean = i.receiveHanger == 1
      })
    } else {
      i.moProcRoadmapProcStationList = []
    }
    // AI排产后 向前合并未合并
    if (i.forwardIntegration == 1) {
      i.moProcRoadmapProcStationList = []
    }
  })
  tableList.value = list
  initSortInfo()
}
const initRouteListInfo = (info) => {
  routeInfo.value = info
  // processId.value = isAdd.value ? null : info.processId
  initTableList(info.moProcRoadmapProcList || [])
  changeProcessInfo()
}
// 路线图详细信息
const getVersionRouteInfo = async (versionId) => {
  loading.value = true
  try {
    const res = await axios.getAction("/api/mo/mo-proc-roadmap/get", { id: versionId })
    emits('initFormInfo', res.data || {})
    initRouteListInfo(res.data || {})
  } catch {
    routeInfo.value = {}
  }
  loading.value = false
}
const showMsg = (record, type) => {
  if (type == 'all') {
    return ['colorList', 'sizeList', 'poList', 'cutterNoList', 'tailorBillList'].some(i => record[i] && record[i].length)
  } else {
    return record[`${type}List`] && record[`${type}List`].length
  }
}
const onChooseProcess = (list, processVersionId) => {
  list.forEach((i, index) => {
    i.sort = index + 1
  })
  initTableList(list, true)
  changeProcessInfo()
  // processOption.value = tableList.value.filter(i => i.effect)
  processId.value = processVersionId
}

defineExpose({
  // processId,
  dataAll,
  tableList
})
watch(() => props.roueteVersionId, (newVal) => {
  tableList.value = []
  originSortList.value = []
  if (newVal && !isAdd.value) getVersionRouteInfo(newVal)
}, { deep: true, immediate: true })

watch(() => props.lineStationLists, (newVal) => {
  if (newVal) lineList.value = newVal
}, { deep: true, immediate: true })

watch(() => props.operateType, (newVal) => {
  // disabled.value = newVal == 'view'
  isAdd.value = newVal == 'add'
  isEdit.value = newVal == 'edit'
}, { deep: true, immediate: true })

watch(() => props.dataAll, (newVal) => {
  dataAll.value = props.dataAll
  tableList.value = newVal.ieRoadmapProcRoadmapVO.moProcRoadmapProcList

  // AI排产后的站点接收衣架选框未展示
  initTableList(newVal.ieRoadmapProcRoadmapVO.moProcRoadmapProcList || [])
  // tableList.value = newVal.ieRoadmapProcRoadmapVO.moProcRoadmapProcList.moProcRoadmapProcStationList
  processSelectList.value = newVal.ieRoadmapVO
  // console.log(newVal,'-----------------')

}, { deep: true, immediate: true })

onMounted(async ()=>{
  const resStaff = await axios.postAction('/api/basic/staff/list')
  if (resStaff.success) staffList.value = resStaff.data
})
</script>